//
//  VideoViewController.m
//  ExploreWorld
//
//  Created by dlios on 15/7/13.
//  Copyright (c) 2015年 chenlin. All rights reserved.
//

#import "VideoViewController.h"
#import  "Header.h"
#import "ListenModel.h"
#import "ListenNormalTableViewCell.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
//自定义weatherButton
#import "TitleWeatherButton.h"

#import "WeatherViewController.h"
@interface VideoViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation VideoViewController

-(void)loadView
{
    [super loadView];
    [self createTitleScroll];
    [self creteLivingButton];
    [self createlistenTableView];
    [self tableNetRequest];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 自定义导航栏返回按钮
    TitleWeatherButton *navButton = [[TitleWeatherButton alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //[navButton setBackgroundColor:[UIColor greenColor]];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];
 }
// 导航栏天气按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    
    WeatherViewController *weather = [[WeatherViewController alloc]init];
   // [self.navigationController pushViewController:weather animated:YES];
    [self.navigationController presentViewController:weather animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
 }
- (void)dealloc
{
    [self.titleScroll release];
    [self.datePicker release];
    [self.table release];
    [self.date release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.videoList = [NSMutableArray array];
    }
    return  self;
}



#pragma mark -
#pragma mark 试听界面的滚动视图
- (void)createTitleScroll
{
    self.titleScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20,WIDTH, WIDTH / 2)];
    [self.titleScroll setContentSize:CGSizeMake(self.view.frame.size.width * 5, 0)];
    [self.titleScroll setBackgroundColor:[UIColor grayColor]];
    [self.titleScroll setPagingEnabled:YES];
    self.titleScroll.delegate = self;
    [self.view addSubview:self.titleScroll];
    [self.titleScroll release];
}

#pragma mark -
#pragma mark 创建中央直播按钮
- (void)creteLivingButton
{
    //创建时间选择器的按钮
    UIButton *dateChoose = [[UIButton alloc]initWithFrame:CGRectMake(70, self.view.frame.size.width / 2 + 20, 60, 30)];
    [dateChoose setTitle:@"往期" forState:UIControlStateNormal];
    [dateChoose setBackgroundColor:[UIColor purpleColor]];
    [dateChoose addTarget:self action:@selector(createDatePicker:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dateChoose];
    [dateChoose release];
}

//点击往期按钮，创建UiDatePicker
- (void)createDatePicker:(id)sender
{
    //获取当前区域
    NSLocale *China = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    
    
    
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 200, self.view.frame.size.width, 200)];
    //将时间选择器的区域设置为中国
    [self.datePicker setLocale:China];
    
    [self.datePicker setBackgroundColor:[UIColor grayColor]];
    [self.datePicker setDatePickerMode: UIDatePickerModeDate];
    [self.datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.datePicker];
    [self.datePicker release];
    
    
    
}


//当前值一旦变化，调用此方法
- (void)dateChange:(id)sender
{
    UIDatePicker *control = (UIDatePicker *)sender;
    self.date = control.date;
    // NSLog(@"%@",self.date);
    [self searchNewsByDate];
}

#pragma mark - 输入日期，搜索新闻内容（先对self.date进行字符串截取，然后拼接网址，网络请求，加载数据）
- (void)searchNewsByDate
{
    NSString *date = [NSString stringWithFormat:@"%@",self.date];
  //  NSLog(@"%@",date);
    
    NSArray *array = [date componentsSeparatedByString:@" "];
    NSString *str = array[0];
    NSString *year = [str substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [str substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [str substringWithRange:NSMakeRange(8, 2)];
    NSString *pickDate = [NSString stringWithFormat:@"%@%@%@",year,month,day];
    NSLog(@"%@",pickDate);
    
}



#pragma mark -
#pragma mark 创建收听界面的tableView
-(void)createlistenTableView
{
    float x = WIDTH / 2 + 50;
    self.table = [[UITableView alloc]initWithFrame:CGRectMake( 0, WIDTH / 2 + 50, WIDTH, HEIGHT - 50 - WIDTH / 2) style:UITableViewStylePlain];
    [self.table setRowHeight:x];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    
}

//tableView两个必须实现的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellnormal = @"cellnormal";
    
    ListenModel *model = [self.videoList objectAtIndex:indexPath.row];
    
    ListenNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellnormal];
    if (!cell) {
        cell = [[ListenNormalTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellnormal];
    }
    cell.titleLable.text = model.title;
    [cell.cellImage  sd_setImageWithURL:[NSURL URLWithString:model.image]];
    return cell;
}

//tableView的网络请求
-(void)tableNetRequest
{
    //从新闻联播APP抓取借口，把请求到的数组存放到bodyList数组里
    //请求地址：http://hot.news.cntv.cn/index.php?controller=lanmu&action=getlastvideolist&id=PAGE1354766409225382&n=50
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    //test http://hot.news.cntv.cn/index.php?controller=lanmu&action=getvideolist&id=PAGE1354766409225382&n=50&time=20150712
    //ture http://hot.news.cntv.cn/index.php?controller=lanmu&action=getlastvideolist&id=PAGE1354766409225382&n=50
    
    NSString *str1 = [NSString stringWithFormat:@"http://hot.news.cntv.cn/index.php?controller=lanmu&action=getlastvideolist&id=PAGE1354766409225382&n=50"] ;
    
    [manager1 GET:str1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = operation.responseData;
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *videoListArray = [BigDic objectForKey:@"videoList"];
        for (NSMutableDictionary *smallDic  in videoListArray) {
            ListenModel *model = [[ListenModel alloc]init];
            model.title = [smallDic objectForKey:@"videoTitle"];
            model.image = [smallDic objectForKey:@"videoImage"];
            model.videoID = [smallDic objectForKey:@"videoPlayID"];
            [self.videoList addObject:model];
        }
        [self.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}



#pragma mark -
#pragma maek 点击cell在当前cell的位置创建播放界面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.streamPlayer.view removeFromSuperview];
   UITableViewCell *cell =   [tableView cellForRowAtIndexPath:indexPath];
   // NSLog(@"%f",cell.frame.origin.x);
 //   NSLog(@"%f",cell.frame.origin.y);
    int  x = cell.frame.origin.x;
    int y = cell.frame.origin.y;
   // NSLog(@"%d,%d",x,y);
    
    ListenModel *model = [self.videoList objectAtIndex:indexPath.row];
 //   NSLog(@"%@",model.videoID);
   // http://a.ali.dongting.com/81fb4aeef6576156/1437226333/m4a_32_10/d0/4b/d04ccfc7680006224863d04fccdfb84b.m4a?s=t
    NSString *str = @"http://a.ali.dongting.com/81fb4aeef6576156/1437226333/m4a_32_10/d0/4b/d04ccfc7680006224863d04fccdfb84b.m4a?s=t";
   // NSString *str = [NSString stringWithFormat:@"http://asp.cntv.lxdns.com/asp/hls/200/0303000a/3/default/%@/200.m3u8",model.videoID];
  //  NSLog(@"%@",str);
    NSURL *streamURL = [NSURL URLWithString:str];
    
    //NSURL *streamURL = [NSURL URLWithString:@"http://192.168.113.152:8090/plug_in/M3u8Mod/LiveStream.m3u8?ClientID=7630&ChannelID=pa://cctv_p2p_hdcctv1"];
    self.streamPlayer = [[MPMoviePlayerController alloc] initWithContentURL:streamURL];
    [self.streamPlayer.view setFrame:self.view.bounds];
    self.streamPlayer.controlStyle =MPMovieControlStyleEmbedded;
    [self.streamPlayer.view setFrame:CGRectMake(x, y,cell.frame.size.width,cell.frame.size.width/2)];
    [self.table addSubview: self.streamPlayer.view];
    [self.streamPlayer play];
}







@end
